#pragma once

#include "Socket.hpp"
#include "Protocol.hpp"
#include "NetCal.hpp"
#include "Connection.hpp"

#include <functional>

using process_t = std::function<std::shared_ptr<Response>(std::shared_ptr<Request>)>;

class PackageParse
{
public:
    PackageParse(process_t process) : _process(process)
    {
    }
    void Excute(Connection *conn)
    {
        while (1)
        {
            if(conn->Inbuffer().empty()) break;
            std::string cmd = Decode(conn->Inbuffer());
            if (cmd.empty())
            {
                std::cout << "cmd is empty" << std::endl;
                continue;
            }
            std::cout << "cmd: " << cmd << std::endl;

            auto req = Factory::BuildRequestDefault();
            req->DeSerialize(cmd);

            auto resp = _process(req);

            std::string ret;
            resp->Serialize(&ret);
            if (ret.empty())
                continue;

            ret = Encode(ret);

            // sockfd->Send(ret);
            // std::cout<<"Send: "<<ret<<std::endl;
            conn->AppendOutbuffer(ret);
        }
        if (!conn->Outbuffer().empty())
            conn->_R->EnableConnrctionReadWrite(conn->Sockfd(), 1, 1);
    }

private:
    process_t _process;
};
